package service

import (
	"fmt"
	assetapi "github.com/hyperledger/fabric-samples/asset-kx/chaincode-go/chaincode/asset/api"
	assetruleapi "github.com/hyperledger/fabric-samples/asset-kx/chaincode-go/chaincode/assetrule/api"
	"github.com/shopspring/decimal"
)

//assetType-ruleExpression:ruleCalculator
var ruleCalculator map[string]map[string]func(assetapi.Asset, *assetruleapi.AssetRule) (interface{}, error)

func init() {
	ruleCalculator = make(map[string]map[string]func(assetapi.Asset, *assetruleapi.AssetRule) (interface{}, error))
	ruleCalculator["BusinessTicket"] = make(map[string]func(assetapi.Asset, *assetruleapi.AssetRule) (interface{}, error))
	ruleCalculator["BusinessTicket"]["assetAmount*k"] = func(ast assetapi.Asset, rule *assetruleapi.AssetRule) (interface{}, error) {
		if k, found := rule.RuleParam["k"]; found {
			bt, ok := ast.(*assetapi.BusinessTicket)
			if !ok {
				return nil, fmt.Errorf("can not calculate with :%s", ast)
			}
			assetAmountD, err := decimal.NewFromString(bt.AssetAmount())
			if err != nil {
				return nil, err
			}
			kD, err := decimal.NewFromString(k)
			if err != nil {
				return nil, err
			}
			return assetAmountD.Mul(kD).String(), nil
		} else {
			return nil, fmt.Errorf("can not find param k")
		}
	}
}
